﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using GoodMan.Tool.Framework;
using GoodMan.Portal.WebLogic;
using GoodMan.Portal.Web.Models;
using System.Drawing;
using GoodMan.Portal.Biz;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Core.HitMonitor;
using GoodMan.Infrastructure.Entities;
using GoodMan.Infrastructure.Entities.Repository;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Core.NoticeManager;
using GoodMan.Core;
using System.Text;
using System.Data;
using GoodMan.Tool.Configration;

namespace GoodMan.Portal.Web.Controllers
{
    [Warp]
    [ErrorHandle]
    [Compress]
    public class HomeController : SiteBaseController
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            //获取商品分类
            ViewBag.ProductCategory = ProductCategoryBiz.GetProductCategoryList();
            //获取各种产品
            //获取套餐
            ViewBag.PackagesProducts = ProductBiz.GetAllProductsByPackages("", 4, 0, 6, "home");
            return View();
        }

        public ActionResult GetFiveSpecial()
        {
            StringBuilder sb = new StringBuilder();
            List<Product> productlist = ProductBiz.GetFiveSepecial();
            if (productlist != null && productlist.Count > 0)
            {
                foreach (var item in productlist)
                {
                    string url = "/shop/ProductItemView?id=" + item.Id;
                    sb.Append("<div class=\"product-sale\">");
                    sb.Append("<a href=\""+url+"\" target=\"_blank\">");
                    sb.Append("<img src=\""+item.Images+"\" alt=\""+item.ProductName+"\" title=\""+item.ProductName+"\" /></a>");
                    sb.Append("<div class=\"p-name\">");
                    sb.Append("<div class=\"media-body\" style=\"height:40px; overflow: hidden\">");
                    sb.Append("<a href=\""+url+"\" target=\"_blank\" title=\""+item.ProductName+"\">"+item.ProductName+"</a></div>");
                    sb.Append("<div>特价：<span class=\"price\" style=\"color:red;\">&yen;" + item.PolicyPrice + "</span></div></div></div>");
                     
                }
            }
            return Content(sb.ToString());
        }

        public ActionResult GetFiveRecommended()
        {
            StringBuilder sb = new StringBuilder();
            List<Product> productlist = ProductBiz.GetFiveRecommended();
            if (productlist != null && productlist.Count > 0)
            {
                foreach (var item in productlist)
                {
                    string url = "/shop/ProductItemView?id=" + item.Id;
                    sb.Append("<div class=\"product\">");
                    sb.Append("<a href=\"" + url + "\" target=\"_blank\">");
                    sb.Append("<img src=\"" + item.Images + "\" alt=\"" + item.ProductName + "\" title=\"" + item.ProductName + "\" /></a>");
                    sb.Append("<div class=\"p-name\">");
                    sb.Append("<div class=\"media-body\" style=\"height:40px; overflow: hidden\">");
                    sb.Append("<a href=\"" + url + "\" target=\"_blank\" title=\"" + item.ProductName + "\">" + item.ProductName + "</a></div>");
                    sb.Append("<div>推荐价：<span class=\"price\" style=\"color:red;\">&yen;" + item.DefaulSalePrice + "</span></div></div></div>");

                }
            }
            return Content(sb.ToString());
        }

        public ActionResult GetFiveGroupBuy()
        {
            StringBuilder sb = new StringBuilder();
            List<Product> productlist = ProductBiz.GetFiveGroupBuy();
            if (productlist != null && productlist.Count > 0)
            {
                foreach (var item in productlist)
                {
                    string url = "/shop/ProductItemView?id=" + item.Id;
                    sb.Append("<div class=\"product\">");
                    sb.Append("<a href=\"" + url + "\" target=\"_blank\">");
                    sb.Append("<img src=\"" + item.Images + "\" alt=\"" + item.ProductName + "\" title=\"" + item.ProductName + "\" /></a>");
                    sb.Append("<div class=\"p-name\">");
                    sb.Append("<div class=\"media-body\" style=\"height:40px; overflow: hidden\">");
                    sb.Append("<a href=\"" + url + "\" target=\"_blank\" title=\"" + item.ProductName + "\">" + item.ProductName + "</a></div>");
                    sb.Append("<div>团购价：<span class=\"price\" style=\"color:red;\">&yen;" + item.DefaulSalePrice + "</span></div></div></div>");

                }
            }
            return Content(sb.ToString());
        }

        public ActionResult GetFiveExchange()
        {
            StringBuilder sb = new StringBuilder();
            List<Product> productlist = ProductBiz.GetFiveExchange();
            if (productlist != null && productlist.Count > 0)
            {
                foreach (var item in productlist)
                {
                    string url = "/shop/ProductItemView?id=" + item.Id;
                    sb.Append("<div class=\"product\">");
                    sb.Append("<a href=\"" + url + "\" target=\"_blank\">");
                    sb.Append("<img src=\"" + item.Images + "\" alt=\"" + item.ProductName + "\" title=\"" + item.ProductName + "\" /></a>");
                    sb.Append("<div class=\"p-name\">");
                    sb.Append("<div class=\"media-body\" style=\"height:40px; overflow: hidden\">");
                    sb.Append("<a href=\"" + url + "\" target=\"_blank\" title=\"" + item.ProductName + "\">" + item.ProductName + "</a></div>");
                    sb.Append("<div>兑换积分：<span class=\"price\" style=\"color:red;\">" + item.Integral + "</span></div></div></div>");

                }
            }
            return Content(sb.ToString());
        }

        public ActionResult module()
        {
            return View();
        }
        public ActionResult product()
        {
            return View();
        }

        public ActionResult SampleEditor()
        {
            return View();
        }
        public ActionResult ImageUpload()
        {
            return View();
        }
        public ActionResult Select()
        {
            List<Object> data = new List<object>() { 
                new {value=1,name="第一个",children=new List<object>(){ new {value=11,name="第一个子类1"},new {value=11,name="第一个子类2"},new {value=11,name="第一个子类3"} }},
                new {value=5,name="第二个",children=new List<object>(){ new {value=51,name="第二个子类1"},new {value=52,name="第二个子类2"},new {value=53,name="第二个子类3"} }},
                new {value=10,name="第三个",children=new List<object>(){ new {value=101,name="第三个子类1"},new {value=102,name="第三个子类2"},new {value=104,name="第三个子类3"} }}
            };
            ViewBag.List = data.ToJson();
            return View();
        }

        public ActionResult error()
        {
            return View();
        }
        public ActionResult notfound()
        {
            return View();
        }
        public ActionResult forbidden()
        {
            return View();
        }
        /// <summary>
        /// 更新在线状态
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public string refresh()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                var user = new User().Find(HttpContext.User.Identity.Name);
                if (user != null && user.SystemRole == UserRole.Staff)
                {
                    int dId = SupportBiz.IsOnDuty(user.UserName);
                    SupportBiz.RefreshOnline(user.UserName);
                    if (dId != -999)
                    {
                        List<DutyMessage> message = SupportBiz.GetDutyNotice(dId, user.UserName);
                        if (message != null)
                        {
                            if (message.Any()) 
                            { 
                            
                            }
                            return message.ToJson();
                        }
                    }
                }
            }
            return "[]";
        }
        public void setOnlineState(int state)
        {
            SupportBiz.UpdateOnlineState(HttpContext.User.Identity.Name,
                state == 1 ? OnlineState.在线 : OnlineState.离线);
        }
        #region
        public void commonUpload()
        {
            var file = System.Web.HttpContext.Current.Request.Files[0];
            string result = "";
            string basedir = "/content/commonImage/";
            string filePath = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                }
                var fileinfo = new FileInfo(file.FileName);
                filePath = basedir + Guid.NewGuid().ToString() + fileinfo.Extension;
                file.SaveAs(HttpContext.Server.MapPath(filePath));
            }
            if (!String.IsNullOrEmpty(filePath))
            {
                result = new
                {
                    url = filePath,
                    title = "",
                    original = "",
                    state = "SUCCESS"
                }.ToJson();
                HttpContext.Response.Write(result);
            }
        }
        public void SWFPrepareUpload()
        {
            new UploadTool().SWFPrepareUpload();
        }
        public void SWFUpload(string msg, string imgs)
        {
            string[] img = imgs.Split(';');
            List<SWFUploadItem> items = new List<SWFUploadItem>();
            foreach (var item in img)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    string[] piece = item.Split(',');
                    if (piece.Length != 3)
                    {
                        continue;
                    }
                    string newPath = piece[2].Replace("/temp/", "/customer/");
                    try
                    {
                        var fileinfo = new FileInfo(Server.MapPath(newPath));
                        if (!System.IO.Directory.Exists(fileinfo.Directory.ToString()))
                        {
                            System.IO.Directory.CreateDirectory(fileinfo.Directory.ToString());
                        }
                        //FileStream fs = new FileStream(Server.MapPath(piece[2]), FileMode.Open);
                        //System.Drawing.Image newImage = new System.Drawing.Bitmap(fs);

                        ////保存缩略图                  
                        //newImage.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);

                        System.IO.File.Copy(
                            Server.MapPath(piece[2]),
                           Server.MapPath(newPath), true);
                        System.IO.File.Delete(Server.MapPath(piece[2]));
                        items.Add(new SWFUploadItem()
                        {
                            name = piece[1],
                            path = newPath,
                            horizontal = piece[0]
                        });
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            Response.Write(items.ToJson());
        }
        public ActionResult option()
        {
            SupportBiz.Option();
            return View();
        }
        #endregion

        #region 信息发布
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="oper">1: 按发布时间排序  2：按点击率排序</param>
        /// <returns></returns>
        public ActionResult PubInfoList(int page=0, int oper=0)
        {
            var pubinfoList = CollegeBiz.GetAllPubInfo(oper, page, 10);
            ViewBag.PubInfo = pubinfoList;
            return View();
        }

        /// <summary>
        /// 发布信息详情
        /// </summary>
        /// <returns></returns>
        public ActionResult InfoDetails(string id)
        {
            InfoHitPack infohit = HitMonitor.Instance(HitName.Information, id).GetValue<InfoHitPack>(true, 1);
            Information info = new Information().Find(id);
            info.CTR = infohit.CTR;
            ViewBag.SpecPubInfo = info;
            return View();
        }
        #endregion

        public ActionResult detail(int id)
        {
            SiteResource.ArticleItem item = null;
            item = SiteResource.SiteArticles.AboutUs.Items.FirstOrDefault(c => c.Id == id.ToString());
            if (item == null)
            {
                item = SiteResource.SiteArticles.Cooperation.Items.FirstOrDefault(c => c.Id == id.ToString());
                if (item == null)
                {
                    item = SiteResource.SiteArticles.Delivery.Items.FirstOrDefault(c => c.Id == id.ToString());
                    if (item == null)
                    {
                        item = SiteResource.SiteArticles.ShoppingGuide.Items.FirstOrDefault(c => c.Id == id.ToString());
                    }
                }
            }
            ViewBag.ArticleTitle = item.Title;
            ViewBag.ArticleContent = item.Content;
            return View();
        }
        public ActionResult noticedetail(int id)
        {
            var notice = new Notice().Find(id.ToString());
            ViewBag.ArticleTitle = notice.Title;
            ViewBag.ArticleContent = notice.Content;
            return View();
        }
    }
}
